//
//  AddCarController.m
//  HuLaQuan
//
//  Created by hok on 3/16/16.
//  Copyright © 2016 yuwubao. All rights reserved.
//

#import "AddCarController.h"

//Cells
#import "YuTypeInfoCell.h"
#import "ConfirmButtonCell.h"
#import "CarSelectionCell.h"
#import "GenericHintCell.h"

//labels
#import "YuUserCellLabel.h"

//导入头文件
#import <BaiduMapAPI/BMapKit.h>

@interface AddCarController ()<UITextFieldDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>

@property (nonatomic,strong) NSArray *items;

@property (nonatomic, strong) NSString *cardID;

@property (nonatomic, strong) NSString *buildingID;

@property (nonatomic, strong) NSString *realName;

@property (nonatomic) BOOL isSavingCarInfo;

@property(strong,nonatomic) BMKLocationService *locService;

@property(strong,nonatomic) BMKGeoCodeSearch *geocodesearch;
@end

static NSString * const YuTypeInfoCellIdentifier = @"YuTypeInfoCell";
static NSString * const ConfirmButtonCellIdentifier = @"ConfirmButtonCell";
static NSString * const CarSelectionCellIdentifier = @"CarSelectionCell";
static NSString * const GenericHintCellIdentifier = @"GenericHintCell";

@implementation AddCarController

- (NSArray *)items
{
    if (!_items) {
        _items = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"AddCarItems" ofType:@"plist"]];
    }
    return _items;
}
- (void)setupUI
{
    [self setupNavBackButton];
    
    [self setupFooterForTableView];
    
    [self.tableView registerNib:[YuTypeInfoCell nib] forCellReuseIdentifier:YuTypeInfoCellIdentifier];
    [self.tableView registerNib:[ConfirmButtonCell nib] forCellReuseIdentifier:ConfirmButtonCellIdentifier];
    [self.tableView registerNib:[CarSelectionCell nib] forCellReuseIdentifier:CarSelectionCellIdentifier];
    [self.tableView registerNib:[GenericHintCell nib] forCellReuseIdentifier:GenericHintCellIdentifier];
    
    self.title = @"车辆详情";
    
    [self addObserver:self forKeyPath:@"isSavingCarInfo" options: NSKeyValueObservingOptionNew context:nil];
    
    self.isSavingCarInfo = YES;
    if([CLLocationManager locationServicesEnabled])
    {
        NSLog(@"allow");
    }
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    //启动LocationService
    [_locService startUserLocationService];
    
    
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    //编码服务的初始化(就是获取经纬度,或者获取地理位置服务)
    _geocodesearch.delegate = self;
//    NSError *error;
//    NSString *string = [[NSString alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"BaiduMap_cityCode" ofType:@"txt"] encoding:NSUTF16StringEncoding error:&error];
//    NSLog(@"loc loc %d",[string rangeOfString:@"武汉"].location
//          );
}

- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    NSLog(@"heading is %@",userLocation.heading);
  

    
//    isGeoSearch = false;
   }

-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        NSString* titleStr;
        NSString* showmeg;
        titleStr = @"反向地理编码";
        showmeg = [NSString stringWithFormat:@"%@",item.title];
        NSLog(@"%@ %@",showmeg , result.addressDetail.city);
        
        
        
      //  self.addr.text = showmeg;
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:titleStr message:showmeg delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",nil];
        [myAlertView show];
    }
}
//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};//初始化
    if (userLocation.location.coordinate.longitude!= 0
        && userLocation.location.coordinate.latitude!= 0) {
        //如果还没有给pt赋值,那就将当前的经纬度赋值给pt
        pt = (CLLocationCoordinate2D){userLocation.location.coordinate.latitude,
            userLocation.location.coordinate.longitude};
    }
    CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
    
//    [geoCoder reverseGeocodeLocation:userLocation completionHandler:^(NSArray *placemarks, NSError *error) {
//        for (CLPlacemark * placemark in placemarks) {
//            NSDictionary *test = [placemark addressDictionary];
//            // Country(国家) State(城市) SubLocality(区) Name全称
//            NSLog(@"%@", [test objectForKey:@"Name"]);
//        }
//    }];
    
    BMKCityListInfo *record = [[BMKCityListInfo alloc] init];
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反编码请求
    reverseGeocodeSearchOption.reverseGeoPoint = pt;//设置反编码的店为pt
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];//发送反编码请求.并返回是否成功
    if(flag)
    {
        NSLog(@"反geo检索发送成功");
    }
    else
    {
        NSLog(@"反geo检索发送失败");
    }
    
    [_locService stopUserLocationService];

}
#pragma mark UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return kNormalCellHeight;
    }else{
        return kConfirmButtonCellHeight;
    }
    
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.items.count;
    }else{
        return 1;
    }
    
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 40;
    }else{
        return 0.00001;
    }
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

{
    if (section == 0) {
        CGRect frameRect = CGRectMake(25, 0, 200, 40);
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        YuUserCellLabel *textSection = [[YuUserCellLabel alloc] initWithFrame:frameRect];
        textSection.text = @"请绑定持卡人信息";
        [view addSubview:textSection];
        return view;
    }else{
        return nil;
    }
    
    
    
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
        if (indexPath.row == self.items.count - 1) {
            CarSelectionCell *cell = [tableView dequeueReusableCellWithIdentifier:CarSelectionCellIdentifier
                                                                     forIndexPath:indexPath];
            cell.titleLabel.text = self.items[indexPath.row][@"title"];
          //  cell.isSelected = self.isSavingCarInfo;
            
            return cell;
        }else{
            YuTypeInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:YuTypeInfoCellIdentifier
                                                                   forIndexPath:indexPath];
            cell.textField.placeholder = self.items[indexPath.row][@"placeholder"];
            [cell.textField addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
            cell.textField.tag = indexPath.row;
            cell.textField.delegate = self;
            cell.titleLabel.text = self.items[indexPath.row][@"title"];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            
            if ([self.items[indexPath.row][@"title"] isEqualToString:@"小区"]) {
                if (self.selectedEstateInfo) {
                    cell.textField.text = self.selectedEstateInfo [@"communityName"];
                }else{
                    cell.textField.text = self.items[indexPath.row][@"placeholder"];
                }
                
                cell.textField.enabled = NO;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                cell.selectionStyle = UITableViewCellSelectionStyleDefault;
            }

            return cell;
        }
        
        
    }else if (indexPath.section == 1){
        ConfirmButtonCell *cell = [tableView dequeueReusableCellWithIdentifier:ConfirmButtonCellIdentifier
                                                                  forIndexPath:indexPath];
        
        [cell.confirmButton setTitle:@"下一步" forState:UIControlStateNormal];
        
        cell.banksButton.hidden = YES;
        
        
        __weak typeof (self) weakSelf = self;
        cell.confirm = (ClickBlock)^(){
            [weakSelf tapNextButton];
        };
        
//        if (self.userName.length && self.cardNumber.length) {
//            cell.confirmButton.enabled = YES;
//        }else{
//            cell.confirmButton.enabled = NO;
//        }
        
        return cell;
    }else{
        GenericHintCell *cell = [tableView dequeueReusableCellWithIdentifier:GenericHintCellIdentifier
                                                                forIndexPath:indexPath];
        cell.hintLabel.text = @"说明：\n 1.保存车辆信息：将您的车辆信息在APP中显示； 反之不保存，您每次使用需要手动输入。";
        return cell;
    }
    
    
    
    
}

#pragma mark - TextField Delegate
- (void)textFieldWithText:(UITextField *)textField
{
    switch (textField.tag) {
        case 0:
            self.cardID = textField.text;
            break;
        case 2:
            self.buildingID = textField.text;
        case 3:
            self.realName = textField.text;
            break;
        default:
            break;
    }
}
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    textField.placeholder = @"";
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    
    textField.placeholder = self.items[textField.tag][@"placeholder"];

//    if (self.userName.length == 0 || self.cardNumber.length ==0) {
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:2 inSection:0];
//        ConfirmButtonCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
//        cell.confirmButton.enabled = NO;
//    }
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
#pragma mark - KVO
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0 && indexPath.row == (self.items.count -1)) {
        self.isSavingCarInfo = !self.isSavingCarInfo;

    }
    
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    CarSelectionCell * cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:self.items.count - 1 inSection:0]];
    cell.isSelected = [change[@"new"] boolValue];

}
#pragma mark - Button Events
- (void)tapNextButton
{
    NSLog(@"%@ %@ %@", self.cardID , self.buildingID, self.realName);
}

#pragma mark - Life Cycle
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
    
    [self removeObserver:self forKeyPath:@"isSavingCarInfo"];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
